#include"UdpServer.hpp"
#include<iostream>
#include<string>
#include<sys/types.h>
#include<sys/socket.h>
#include<cerrno>
#include<cstring>
#include<string.h>
#include"Log.hpp"
#include"LockGuard.hpp"
#include<arpa/inet.h>
#include<cstdlib>
#include<netinet/in.h>

void Usage(std::string proc)
{
    std::cout<<"Usage: \n\t"<<proc<<" serverip serverport"<<std::endl;
}

int main(int argc,char* argv[])
{
    if(argc!=3)
    {
        Usage(argv[0]);
        exit(1);
    }

    std::string serverip=argv[1];
    uint16_t serverport=atoi(argv[2]);

    //1.创建sockfd
    int sockfd=socket(AF_INET,SOCK_DGRAM,0);
    if(sockfd<0)
    {
        std::cerr<<"socket error"<<std::endl;
        exit(1);
    }

    //2.填充服务器的网络信息结构体
    struct sockaddr_in server;
    bzero(&server,sizeof(server));
    server.sin_family=AF_INET;
    server.sin_port=htons(serverport);
    server.sin_addr.s_addr=inet_addr(serverip.c_str());
    //3.发送数据
    std::string message;
    while(true)
    {
        std::cout<<"Please Enter：#";
        std::getline(std::cin,message);
        sendto(sockfd,message.c_str(),message.size(),0,(struct sockaddr*)&server,sizeof(server));

        struct sockaddr_in peer;
        socklen_t len=sizeof(peer);
        char buffer[1024];
        ssize_t n=recvfrom(sockfd,buffer,sizeof(buffer)-1,0,(struct sockaddr*)&peer,&len);
        if(n>0)
        {
            buffer[n]=0;
            std::cout<<"Server Echo# "<<buffer<<std::endl;
        }
    }
    return 0;
}